package util

import (
	"encoding/json"
	"io"
	"net/http"
	"net/url"
)

const (
	HttpHeaderAuthorization = "Authorization"
	HttpGet                 = "GET"
	HttpPost                = "POST"
	HttpPut                 = "PUT"
	HttpDelete              = "DELETE"
	HttpPatch               = "PATCH"
)

type HttpRequestHelper interface {
	Get(url string, params map[string]any) map[string]any
}

func NewHttpRequestHelper() HttpRequestHelper {
	return httpRequestHelper{}
}

func (httpRequestHelper) Get(route string, params map[string]any) map[string]any {
	// Prepares get parameters.
	parameters := url.Values{}

	for key, value := range params {
		parameters.Add(key, value.(string))
	}

	// Prepares myUrl.
	myUrl, _ := url.Parse(route)
	myUrl.RawQuery = parameters.Encode()

	// Prepares empty result and makes request.
	result := map[string]any{}
	response, err := http.Get(myUrl.String())

	// If error happens returns empty result.
	if err != nil {
		return result
	}

	defer response.Body.Close()

	// Reads data and parses it to map format.
	data, _ := io.ReadAll(response.Body)
	json.Unmarshal(data, &result)

	return result
}

type httpRequestHelper struct{}
